import { PureComponent } from 'react';
import { TreeSelect } from 'antd';
const { TreeNode } = TreeSelect;

class SelectWorkTree extends PureComponent {
  state = {
    value: undefined,
    treeData: [
    	{ title: '单位', key: '000000000000',dept_id:'',dept_code:"0000" },
    ],
   };

  constructor(props) {
	  super(props);
		this.state.value = props.deptValues;
  }
  
  onChange = (value,label,extra) => {
  	
  	if(extra.triggerNode.props.dataRef.key != '000000000000') {
	  	const { selectedWorkTreeValue } = this.props;
	    selectedWorkTreeValue(extra);
	    this.setState({ value });
  	}
  	
  };
  
  onSelect = value => {
  	
  }
  
  onTreeExpand = expandedKeys => {
  	
  }
  
  onLoadData = (treeNode) => {
	    const { dispatch, requestModelName } = this.props;
	    const params = {
	      parentid: treeNode.props.dataRef.key,
	    };
	    return new Promise((resolve) => {
		    if (treeNode.props.children) {
		      resolve();
		      return;
		    }
	    	dispatch({
		        type: requestModelName + "/get_worktree_by_parentid",
		        payload: params,
		        callback: () => {
		          const { selectWorkTree: { list } } = this.props;
		          treeNode.props.dataRef.children = list;
		          this.setState({
		          	treeData: [...this.state.treeData],
		          });
		          resolve();
		        }
	     	});
	    });
  };

	renderTreeNodes = data =>
	    data.map(item => {
		      if (item.children) {
		        return (
		    	    <TreeNode title={item.title} key={item.key} dataRef={item}  value={item.title}>
			            {this.renderTreeNodes(item.children)}
			         </TreeNode>
		        );
		      }
		      return <TreeNode {...item} value={item.title} dataRef={item} title={item.title} key={item.key}/>;
	});
	
  render() {
    return (
      <TreeSelect
      	showSearch
        value={this.state.value}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="请选择"
        treeDefaultExpandAll
        onSelect={this.onSelect}
        onChange={this.onChange}
        onTreeExpand={this.onTreeExpand}
        loadData={this.onLoadData}
      >
       	{this.renderTreeNodes(this.state.treeData)}
      </TreeSelect>
    );
  }
}

export default SelectWorkTree;